package com.park.microprofile.configsource;

import org.eclipse.microprofile.config.spi.ConfigSource;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Logger;

/**
 * 默认本地配置文件配置源
 *
 * @author Aaron
 * @date 2021/7/14 16:08
 */
public class DefaultResourceConfigSource implements ConfigSource {
    private final Logger logger = Logger.getLogger(this.getClass().getName());

    private static final String CONFIG_FILE_LOCATION = "META-INF/microprofile-config.properties";

    private final Map<String, String> defaultConfigMap = new HashMap<>();

    public DefaultResourceConfigSource() {
        init();
    }

    @Override
    public Set<String> getPropertyNames() {
        return defaultConfigMap.keySet();
    }

    @Override
    public String getValue(String propertyName) {
        return defaultConfigMap.get(propertyName);
    }

    @Override
    public String getName() {
        return "Local System Default Config Source ";
    }

    private void init() {
        ClassLoader classLoader = getClass().getClassLoader();
        URL resource = classLoader.getResource(CONFIG_FILE_LOCATION);
        if (resource == null) {
            logger.info("未找到默认路径下的配置文件." + CONFIG_FILE_LOCATION);
            return;
        }
        try (InputStream inputStream = resource.openStream()) {
            Properties properties = new Properties();
            properties.load(inputStream);
            for (Map.Entry<Object, Object> entry : properties.entrySet()) {
                Object key = entry.getKey();
                Object value = entry.getValue();
                defaultConfigMap.put(key.toString(), value == null ? null : value.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
